<?php
/**
 * Created by PhpStorm.
 * User: thanatos
 * Date: 2017/11/28
 * Time: 下午2:06
 */

namespace frontend\controllers;

use common\helpers\AjaxHelper;
use common\models\File;
use Yii;
use common\core\Controller;
use yii\filters\VerbFilter;

class MainController extends Controller{
    
    public function behaviors(){
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'upload-img' => ['post'],
                ],
            ],
        ];
    }
    
    public function actionUploadImg()
    {
        if( Yii::$app->request->isAjax ){
            $ids = Yii::$app->request->getBodyParam('serverIds');
            $server_arr = explode(',', trim($ids, '"'));
            $app = Yii::$app->wechat->getApp()->material_temporary;
            $dir = Yii::getAlias('@uploads') . DIRECTORY_SEPARATOR . 'bl';
            foreach( $server_arr as $k => $v ){
                mkdir($dir, 0755, true);
                $filename = $app->download($v, Yii::getAlias('@uploads') . DIRECTORY_SEPARATOR . 'bl');
                // 插入数据库
                $model = new File(['file_path' => '/uploads/bl' . DIRECTORY_SEPARATOR .$filename, 'file_type' => File::WECHAT_TYPE]);
                $model->save();
                $server_img[] = array('path'=>$model->file_path, 'id'=>$model->file_id);
                $server_ids[] = $model->file_id;
                
            }
            $response = new AjaxHelper;
            $response->data = ['server_id' => implode(',', $server_ids), 'server_img' => $server_img];
            return $response;
            
        }
    
    }
}